from __future__ import division

from PyQt4.QtGui import QWidget, QListWidgetItem
from PyQt4.QtCore import *
from PyQt4.Qt import *

from PyQt4.Qwt5 import QwtPlot, QwtPlotCurve, QwtLegend

from netin_gui import Ui_Form

def humanize_bytes(bytes, precision=1):
	"""Return a humanized string representation of a number of bytes.
	Assumes `from __future__ import division`.

	http://code.activestate.com/recipes/577081-humanized-representation-of-a-number-of-bytes/
	
	>>> humanize_bytes(1)
	'1 byte'
	>>> humanize_bytes(1024)
	'1.0 kB'
	>>> humanize_bytes(1024*123)
	'123.0 kB'
	>>> humanize_bytes(1024*12342)
	'12.1 MB'
	>>> humanize_bytes(1024*12342,2)
	'12.05 MB'
	>>> humanize_bytes(1024*1234,2)
	'1.21 MB'
	>>> humanize_bytes(1024*1234*1111,2)
	'1.31 GB'
	>>> humanize_bytes(1024*1234*1111,1)
	'1.3 GB'
	"""

	abbrevs = (
		(1<<50L, 'PB'),
		(1<<40L, 'TB'),
		(1<<30L, 'GB'),
		(1<<20L, 'MB'),
		(1<<10L, 'kB'),
		(1, 'bytes')
	)
	if bytes == 1:
		return '1 byte'
	for factor, suffix in abbrevs:
		if bytes >= factor:
			break
	return '%.*f %s' % (precision, bytes / factor, suffix)

class NetinMonitorWidget(QWidget, Ui_Form): 
	def __init__(self, monitor, interval=2000):
		QWidget.__init__(self)
		self.setupUi(self)
		self.setupList()
		self.monitor = monitor
		self.timer(interval)

		self.curveRX = QwtPlotCurve("RX")
		self.curveRX.attach(self.plot)
		self.curveRX.setPen(QPen(Qt.red))
		self.curveTX = QwtPlotCurve("TX")
		self.curveTX.attach(self.plot)
		self.curveTX.setPen(QPen(Qt.blue))
		self.plot.insertLegend(QwtLegend(), QwtPlot.BottomLegend)

	def setupList(self):
		self.listWidget = self.q_interfacesList
		self.item2obj = dict()
		self.connect(self.listWidget, SIGNAL("itemClicked(QListWidgetItem*)"), lambda i: self.tick())
	
	def timer(self, interval):
		self.timer = QTimer(self)
		self.timer.setInterval(interval)
		self.connect(self.timer, SIGNAL('timeout()'), self.tick)
		self.timer.start()

		self.tick()

	def tick(self):
		interfaces = self.monitor()
		for network in interfaces:
			if not self.listWidget.findItems(network.name, Qt.MatchCaseSensitive):
				# estendere QListWidget e fargli un dizionario item2object
				# stile: item = mylistwidget.additem(obj, 'name')
				#        mylistwidget.get(obj) # == item
				#        mylistwidget.get(item) # == obj
				item = QListWidgetItem(network.name) 
				self.item2obj[item] = network 
				self.listWidget.addItem(item)
		#self.orderByActivity()
		self.updateLabels()

	def updateLabels(self):
		item = self.listWidget.currentItem()#.selectedItem
		if item: 
			obj = self.item2obj[item]

			self.q_bytes_rx.setText( humanize_bytes(obj.RX) )
			self.q_bytes_tx.setText( humanize_bytes(obj.TX) )
			self.q_networkname.setText( str(obj.name) )

			self.updatePlot(obj)

	def updatePlot(self, obj):

		obj.updateDelta()
		self.curveRX.setData(obj.x, obj.historyRX)
		self.curveTX.setData(obj.x, obj.historyTX)
		self.plot.replot()
